# clear working environment
rm(list = ls())

#### load the required packages ####
library(tidyverse)
library(PanelMatch)
library(countrycode)
library(patchwork)

#### load the clean data ####
df <- readRDS("data/dem-transitions-replication-data.rds") %>%
  glimpse()

# create lagged dem, transition indicator, lead variables
df <- df %>%
  mutate(dem = ifelse(v2x_regime > 1, 1, 0)) %>%
  dplyr::group_by(country) %>%
  mutate(dem_lag_1 = dplyr::lag(dem)) %>%
  mutate(regime_lag_1 = dplyr::lag(v2x_regime)) %>%
  mutate(transition = ifelse(dem == 1 & dem_lag_1 == 0, 1, 0)) %>%
  glimpse()

df_year <- df %>%
  dplyr::group_by(year) %>%
  dplyr::summarize(n_transitions = sum(transition, na.rm = TRUE),
            CumPercent = round(cumsum(transition)/sum(transition)*100, 2)) %>%
  mutate(un_region = "All") %>%
  mutate(type = "Global") %>%
  glimpse()

df_year <- df %>%
  dplyr::group_by(year) %>%
  dplyr::summarize(n_transition = sum(transition, na.rm = TRUE), 
            n_democracies = sum(dem, na.rm = TRUE),
            n_countries = n()) %>%
  glimpse()

df_year <- df_year %>%
  mutate(tot_transition = sum(n_transition)) %>%
  mutate(cum_transition = cumsum(n_transition)) %>%
  mutate(percent_transition = round(100*(cum_transition/tot_transition), 2)) %>%
  mutate(percent_dem = round(100*(n_democracies/n_countries), 2)) %>%
  glimpse()

df_region_year <- df %>%
  dplyr::group_by(un_region, year) %>%
  dplyr::summarize(n_transition = sum(transition, na.rm = TRUE), 
            n_democracies = sum(dem, na.rm = TRUE),
            n_countries = n()) %>%
  glimpse()

df_region_year <- df_region_year %>%
  mutate(tot_transition = sum(n_transition)) %>%
  mutate(cum_transition = cumsum(n_transition)) %>%
  mutate(percent_transition = round(100*(cum_transition/137), 2)) %>%
  mutate(percent_dem = round(100*(n_democracies/n_countries), 2)) %>%
  glimpse()

df_region <- df %>%
  dplyr::group_by(un_region) %>%
  dplyr::summarize(n_transition = sum(transition, na.rm = TRUE)) %>%
  glimpse()

df_region <- df_region %>%
  mutate(tot_transition = sum(n_transition)) %>%
  mutate(percent_transition = round(100*(n_transition/tot_transition), 2)) %>%
  glimpse()

# create Figure B.3 for the appendix
p1 <- ggplot(data = df_year) +
  geom_vline(xintercept = c(1946, 1990), linetype = "dashed") +
  geom_line(aes(x = year, y = percent_dem), color = "darkgray", linewidth = 1) +
  geom_line(aes(x = year, y = percent_transition), color = "black", linewidth = 1) +
  annotate("text", x = 1920, y = 85, label = "% of Democratic Transitions", color = "black", size = 4) +
  annotate("text", x = 1920, y = 75, label = "% of Countries that are Democracies", color = "darkgray", size = 4) +
  scale_y_continuous(labels = function(x) paste0(x, "%")) +
  theme_minimal() +
  labs(title = "",
       x = "Year",
       y = "")

# create Figure B.4 for the appendix
p2 <- ggplot(data = df_region_year, aes(x = year, y = percent_transition, color = un_region)) +
  geom_vline(xintercept = c(1946, 1990), linetype = "dashed") +
  geom_line(linewidth = 1) +
  scale_color_manual(values = c("#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e")) +
  scale_y_continuous(labels = function(x) paste0(x, "%")) +
  theme_minimal() +
  theme(legend.position = "bottom") +
  labs(title = "",
       x = "Year", 
       y = "% of Global Transitions",
       color = "UN Region")

# create Figure B.5 for the appendix
p3 <- ggplot(data = df_region_year, aes(x = year, y = percent_dem, color = un_region)) +
  geom_vline(xintercept = c(1946, 1990), linetype = "dashed") +
  geom_line(linewidth = 1) +
  scale_color_manual(values = c("#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e")) +
  scale_y_continuous(labels = function(x) paste0(x, "%")) +
  theme_minimal() +
  theme(legend.position = "bottom") +
  labs(title = "",
       x = "Year", 
       y = "% of Region that is Democratic",
       color = "UN Region")

p1
# save plot
ggsave("figures/global-transition-patterns-1.pdf", width = 8.5, height = 4.5, units = "in", bg = "white")

p2
# save plot
ggsave("figures/global-transition-patterns-2.pdf", width = 6.5, height = 4.5, units = "in", bg = "white")

p3
# save plot
ggsave("figures/global-transition-patterns-3.pdf", width = 6.5, height = 4.5, units = "in", bg = "white")

# patterns of transition in different eras (referenced in the notes of Figure 9 in the main text)
sum(df$transition[df$year >= 1990], na.rm = TRUE) # Post-Cold War: 82 (82/144 = 57%)
sum(df$transition[df$year < 1990], na.rm = TRUE) # Pre-/Cold War: 62 (62/144 = 43%)
sum(df$transition, na.rm = TRUE)

# calculate as percentages of total transitions (referenced in the notes of Figure 9 in the main text)
round((sum(df$transition[df$year >= 1990], na.rm = TRUE)/sum(df$transition, na.rm = TRUE))*100, digits = 2)
round((sum(df$transition[df$year < 1990], na.rm = TRUE)/sum(df$transition, na.rm = TRUE))*100, digits = 2)

# create histogram and bar plot of democracy-years
dem_countries <- df %>%
  dplyr::group_by(country) %>%
  dplyr::summarize(sum_dem = sum(dem, na.rm = TRUE),
            region = first(un_region)) %>%
  glimpse()

dem_countries <- left_join(dem_countries, select(df, country, un_region), by = "country")

# create Figure K.1 for the appendix
p4 <- ggplot(data = dem_countries, aes(x = sum_dem, y = after_stat(density))) +
  geom_histogram(bins = 45) +
  theme_minimal() +
  labs(x = "Number of Years as a Democracy (1900-2014)",
       y = "Density",
       title = "Panel A: Histogram of Democracy-years by Country")

p5 <- ggplot(data = dem_countries, aes(x = country, y = sum_dem)) +
  geom_col() +
  facet_wrap(~region, scales = "free") +
  labs(y = "Number of Years as a Democracy",
       x = "COW Country Code",
       title = "Panel B: Democracy-years by Country and Region") +
  theme_minimal()

p4/p5

# save plot
ggsave("figures/global-democracy-patterns.pdf", width = 10.5, height = 8.5, units = "in", bg = "white")
